import React, { Component } from 'react';
import { Modal, Form, Input } from 'antd';

const FormItem = Form.Item;

class AddForm extends Component {
    // 校验用户名
    checkName = (rule, value, callback) => {
        const { dataSource } = this.props;
        var reg = /(^\s+)|(\s+$)/g;
        if (value) {
            for (var i = 0; i < dataSource.length; i++) {
                if (dataSource[i].username === value) {
                    callback("此用户已存在，请重新设置！")
                }
            }
        } else {
            callback('请输入用户名!');
        }
        if (reg.test(value)) {
            callback('包含空格!');
        }
        callback();
    };

    render() {
        const { addModalVisible, addCancel, addOk, form } = this.props;
        const { getFieldDecorator } = form;
        const FormItemLayout = {
            labelCol: { span: 5 },
            wrapperCol: { span: 16 },
        };
        return (
            <Modal
                visible={addModalVisible}
                title='添加用户'
                okText='添加'
                cancelText='取消'
                onCancel={addCancel}
                onOk={addOk}
            >
                <Form layout="horizontal">
                    <FormItem label="用户名" {...FormItemLayout} hasFeedback>
                        {getFieldDecorator('username', {
                            rules: [{ required: true, validator: this.checkName },
                            { max: 20, message: "最大长度为20!" }],
                        })(
                            <Input />
                        )}
                    </FormItem>
                    <FormItem label="密码" {...FormItemLayout} hasFeedback>
                        {getFieldDecorator('password', {
                            rules: [{ required: true, message: "请输入密码" },
                            { min: 6, message: "最小长度为6!" },
                            { max: 20, message: "最大长度为20!" }],
                        })(
                            <Input type="password"/>
                        )}
                    </FormItem>
                </Form>
            </Modal>
        );
    }
}

const AddModal = Form.create()(AddForm);
export default AddModal;